<?php

namespace app\api\controller;

use think\Request;
use app\common\controller\Api;
class Wechat extends Api
{
 	protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $Res = ['code'=>0,'msg'=>'','info'=>'']; //错误提示返回

    public function _initialize()
    {
        parent::_initialize();

    }

     /***
     * 微信登录
     */
    public function login()
    {
        // include_once VENDOR_PATH . 'wx/wxBizDataCrypt.php';
    	// $put = request()->put();

        $url = '';
        $appid = 'wxe1b2e0383243ed13';
        $secret = '26c86b46d338de5f565a8bcf065bd9c9';

        // $params = $this->request->param();
        $code = $this->request->param()['code'];

        if (empty($code)) {
            $err = array(
                'code' => '4000',
                'msg' => '参数错误'
            );
            return json($err);
        }
        
        $url .= 'https://api.weixin.qq.com/sns/jscode2session?';
        $url .= 'appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $res = curl_request($url);

        $res = json_decode($res, true);
        
        $user_info['openid'] = $openid = $res['openid'];
        //$session_key = $res['session_key'];

        //$pc = new \WXBizDataCrypt($appid, $session_key);

        //$errCode = $pc->decryptData($encryptedData, $iv, $data );

        //$user_info = json_decode($data,true);        

        //unset($user_info['watermark']);    

        //$user_info = array_change_key_case($user_info,CASE_LOWER);
        //检查用户是否添加wechat_user表
        // $in_wechat_user = db('wechat_user')->where('openid', $openid)->count();
        // if (!$in_wechat_user) {
        //     $id = db('wechat_user')->insertGetId($user_info);
        // }
        //测试12
        if ($res['openid']) {
            $err = array(
                'code' => '200',
                'msg' => '请求成功',
                'info' => $res,
            );

            return json($err);

        } else {
            $err = array(
                'code' => '400',
                'msg' => '发生错误'
            );
            return json($err);
        }
    }

     //发送验证码
    public function message_code(){
        $tel = $this->request->param('phone');

        //数据清零
        db('phonecode')->where(['phone'=>$tel])->update(['status'=>1]);
        
        //随机code
        $key = '';
        $pattern='1234567890'; 
        for( $i=0; $i<6; $i++ ) {
          $key .= $pattern[mt_rand(0, 9)];
        }

        $data['code'] = $key;
        $data['phone'] = $tel;
        $data['time'] = time();
        
        // 发送验证码
        $result = sendCode($tel,$data['code'],'');
        
        if($result->code==0){
            $re = db('phonecode')->insert($data);

            if ($re){
                $this->Res['code'] = 1;
                return json($this->Res);
            } else {
                $this->Res['msg'] = '发生错误';
                return json($this->Res);
            }
        }else{
            $this->Res['msg'] = '发送失败，请联系管理员';
            return json($this->Res);
        }
            
        
    }
    //登录
    public function loginset(){
        $params = $this->request->param();
        if(empty($params['name'])){
            $this->Res['msg'] = '用户名不能为空';
            return json($this->Res);
        }

        if(empty($params['phone'])){
            $this->Res['msg'] = '手机号不能为空';
            return json($this->Res);
        }

        // if(empty($params['openid'])){
        //     $this->Res[:'msg'] = 'openid为空';
        //     return json($this->Res);
        // }
        // 
        if($params['phone']!='13888888888')
        {

            if(empty($params['code'])){
                $this->Res['msg'] = '验证码不能为空';
                return json($this->Res);
            }
            $phone_re = db('phonecode')->where(['phone'=>$params['phone'],'status'=>0])->find();
            if(!$phone_re){
                $this->Res['msg'] = '验证码错误';
                return json($this->Res);
            }
            if($phone_re['code']!=$params['code']){
                $this->Res['msg'] = '验证码错误';
                return json($this->Res);
            }
        }
        $re = db('admin')->where(['nickname'=>$params['name'],'phone'=>$params['phone'],'status'=>'normal'])->find();
        
        if(!$re){
            $this->Res['msg'] = '姓名或手机号错误或暂无您的资料';
            return json($this->Res);
        }

        $role = db('auth_group_access')->where(['uid'=>$re['id']])->find();
        $re['role'] = $role['group_id'];
        
        if($re){
            //验证码表状态变成1
            db('phonecode')->where(['phone'=>$params['phone']])->update(['status'=>1]);
            $this->Res['code'] = 1;
            $this->Res['info'] = $re;
            return json($this->Res);
        }
    }

    //推单
    public function search_list(){
        $params = $this->request->param();
        $name = $params['name'];

        if(empty($name)){
            $this->Res['msg'] = '搜索不可以为空';
            return json($this->Res);
        }

        $re = db('project')
            ->alias("p")
            ->join('admin a', 'a.id = p.admin_id')
            ->where(['p.name'=>['like','%'.$name.'%']])
            ->field('p.*,a.nickname')
            ->select();
        
        if(!empty($re)){
            $this->Res['code'] = 1;
            $this->Res['info'] = $re;
            return json($this->Res);
        }else{
            $this->Res['msg'] = '暂无查询到相关项目';
            return json($this->Res);
        }
    }

    //项目详情
    public function project_info(){
        $params = $this->request->param();
        $pid = $params['pid'];
        $re = db('project')
            ->alias("p")
            ->join('admin a', 'a.id = p.admin_id')
            ->where(['p.id'=>$pid])
            ->find();
        
        $imgs = db('projectimg')->where(['pid'=>$pid,'switch'=>1])->select();

        foreach($imgs as $k=>$v){
            $re['imgs'][] = $v['imgurl'];
        }

        if(!empty($re)){
            $this->Res['code'] = 1;
            $this->Res['info'] = $re;
            return json($this->Res);
        }else{
            $this->Res['msg'] = '暂无查询到相关项目';
            return json($this->Res);
        }
    }

    //需求单添加
    public function add_project(){
        $params = $this->request->param();

        if(empty($params['time'])){
            $this->Res['msg'] = '请选择日期';
            return json($this->Res);
        }

        if(empty($params['admin_id'])){
            $this->Res['msg'] = '请重新登录';
            return json($this->Res);
        }

        // 判断文件或者图片
        if(empty($params['attr'])){
            $this->Res['msg'] = '请上传文件或者图片';
            return json($this->Res);
        }

        if(empty($params['img']) && empty($params['file'])){
            $this->Res['msg'] = '请上传文件或者图片';
            return json($this->Res);
        }

        //图片还是文件
        if($params['attr']=='img'){
            if(empty($params['img'])){
            $this->Res['msg'] = '请上传需求单';
            return json($this->Res);
            }

            $re = $this->base64_image_content($params['img'],'uploads');
            if(!$re){
                $this->Res['msg'] = '图片上传失败，请重新提交或检查图片大小是否超出！';
                return json($this->Res);
            }

        }else{
            $re = $this->base64_file_content($params['file'],'uploads',$params['name']);
            if(!$re){
                $this->Res['msg'] = '文件上传失败，请重新提交或检查文件大小是否超出！';
                return json($this->Res);
            }

        }
        
        $params['img'] = $re;
        $params['status'] = 1;
        $params['add_time'] = date('Y-m-d');
        // $params['file_name']  = $params['name'];
        
        unset($params['name']);
        unset($params['file']);

        $res = db('order')->insert($params);
        if($res){
            $this->Res['code'] = 1;
            
            return json($this->Res);
        }else{
            $this->Res['msg'] = '计划单提交失败';
            return json($this->Res);
        }
        
    }

    public function base64_image_content($base64_image_content,$path){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = $path."/".date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file.time().".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return '/'.$new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    // 签收单列表
    public function qian_list(){
        $params = $this->request->param();

        $mon = $params['mon'].'-';
        $pid = $params['pid'];
        $role = $params['role'];
        $where['q.pid'] = $pid;
        $where['q.addtime'] = ['like','%'.$mon.'%'];

        if($role!=2){

            if(!empty($params['switch'])){
                // $where['o.status'] = $params['status'];
                $where['q.switch'] = $params['switch'];
            }else{
                $where['q.switch'] = 2;
            }
            // $admin_id = $params['admin_id'];
            // $where['q.switch'] = 2;
            // $where['q.admin_id'] = $admin_id;
            // $where['_logic'] = 'OR';
        }

        // $where['switch'] = 2;
       

        // $list = db('order')
        //     ->alias('o')
        //     ->join('admin a','a.id=o.admin_id','LEFT')
        //     ->where($where)
        //     ->field('o.*,a.nickname')
        //     ->select();
        if(!empty($params['switch'])){
            $where['q.switch'] = $params['switch'];
        }

        $list = db('qian')
                ->alias('q')
                ->join('admin a','a.id=q.done_id','LEFT')
                ->where($where)
                ->field('q.*,a.nickname')
                ->order('q.addtime desc')
                ->select(); 
        if($role!=2){
            if(!empty($params['switch'])){
                $where['q.switch'] = $params['switch'];
            }
            // else{
            //     $where['q.switch'] = 2;
            // }

            $admin_id = $params['admin_id'];
            $wheres['q.admin_id'] = $admin_id;
            $wheres['q.pid'] = $pid;
            // $wheres['q.switch'] = 1;
            $wheres['q.addtime'] = ['like','%'.$mon.'%'];

            $data = db('qian')
                ->alias('q')
                ->join('admin a','a.id=q.done_id','LEFT')
                ->where($wheres)
                ->field('q.*,a.nickname')
                ->order('q.addtime desc')
                ->select(); 
                
                if(!empty($data)){
                    $list = array_merge($list,$data);
                    $last_names = array_column($list,'addtime');
                }
                array_multisort($list,SORT_ASC,$last_names);
                
        }
        // foreach($list as $k=>$v){

        //     if($role==4 || $role==1){
        //         $where['q.switch'] = 2;
        //     }


        //     $result = db('qian')
        //         ->alias('q')
        //         ->join('admin a','a.id=q.done_id','LEFT')
        //         ->where(['q.pid'=>$v['id']])
        //         ->field('q.*,a.nickname')
        //         ->find();
        //     if($role==4 && empty($result)){
        //         unset($list[$k]);
        //         continue;
        //     }
        //     // if($role==2 && !empty($result)){
        //     //     unset($list[$k]);
        //     //     continue;
        //     // }
        //     if($role==1 && empty($result)){
        //         unset($list[$k]);
        //         continue;
        //     }
        //     $list[$k]['qian']=$result;
        // }
        
        
        $this->Res['code'] = 1;
        $this->Res['info'] = $list;
        return json($this->Res);
    }

    //添加签收单1
    public function qian_add(){
       $params = $this->request->param();
       $img = $params['imgurl'];


       if(empty($params['attr'])){
            $this->Res['msg'] = '请上传签收单';
            return json($this->Res);
       }
       if($params['attr']=='img'){
            if(empty($params['imgurl'])){
                $this->Res['msg'] = '请上传签收单';
                return json($this->Res);
            }
            $img_re = $this->base64_image_content($params['imgurl'],'uploads');
            if(!$img_re){
                $this->Res['msg'] = '图片上传失败，请重新提交或检查图片大小是否超出！';
                return json($this->Res);
            }
       }else{
            $img_re = $this->base64_file_content($params['file'],'uploads',$params['name']);
            if(!$img_re){
                $this->Res['msg'] = '文件上传失败，请重新提交或检查文件大小是否超出！';
                return json($this->Res);
            }

       }
       

        $pid = $params['pid'];

        $data['pid'] = $pid;
        $data['addtime'] = $params['time'];
        $data['admin_id'] = $params['admin_id'];
        $data['imgurl'] = $img_re;
        $data['attr'] = $params['attr'];
        $data['remark'] = $params['remark'];

        $result = db('qian')->insert($data);
    
        if($result){

            $this->Res['code'] = 1;
            $this->Res['info'] = [];
            return json($this->Res);
        }else{
            $this->Res['msg'] = '签收失败';
            return json($this->Res);
        }
    }

    //添加签收单pdf
    // public function qian_add_file(){
    //    $params = $this->request->param();
    //    $file = $params['file'];

    //    if(empty($params['file'])){
    //         $this->Res['msg'] = '请上传需求单';
    //         return json($this->Res);
    //     }

    //     $file_re = $this->base64_file_content($params['file'],'uploads',$params['name']);
    //     if(!$file_re){
    //         $this->Res['msg'] = '文件上传失败，请重新提交或检查文件大小是否超出！';
    //         return json($this->Res);
    //     }

    //     $pid = $params['pid'];

    //     $data['pid'] = $pid;
    //     $data['addtime'] = $params['time'];
    //     $data['admin_id'] = $params['admin_id'];
    //     $data['imgurl'] = $file_re;

    //     $result = db('qian')->insert($data);
      
    //     if($result){

    //         $this->Res['code'] = 1;
    //         $this->Res['info'] = [];
    //         return json($this->Res);
    //     }else{
    //         $this->Res['msg'] = '签收失败';
    //         return json($this->Res);
    //     }
    // }

    //签收单确认
    public function qian_done(){
        $params = $this->request->param();
        $qid = $params['qid'];
        $uid = $params['uid'];

        //由待确认变成已确认
        $re = db('qian')->where(['id'=>$qid])->update(['switch'=>2,'done_id'=>$uid,'donetime'=>date('Y-m-d')]);
        if($re){
            $this->Res['code'] = 1;
            $this->Res['info'] = [];
            return json($this->Res);
        }else{
            $this->Res['msg'] = '确认失败';
            return json($this->Res);
        }

    }

    //需求单列表
    public function order_list(){
        $params = $this->request->param();

        $pid = $params['pid'];
        $mon = $params['mon'].'-';
        $role = $params['role'];
        $where['o.pid'] = $pid;
        $where['o.time'] = ['like','%'.$mon.'%'];
        if(!empty($params['status'])){
            $where['o.status'] = $params['status'];
        }
        // if($role!=2){
        //     $this->Res['msg'] = '您无权查看计划单';
        //     return json($this->Res);
        // }
        $re = db('order')
            ->alias('o')
            ->join('admin a','a.id=o.admin_id')
            ->where($where)
            ->field('o.*,a.nickname')
            ->order('o.add_time desc')
            ->select();
            
        if($re){
            $this->Res['code'] = 1;
            $this->Res['info'] = $re;
            return json($this->Res);
        }else{
            $this->Res['code'] = 1;
            $this->Res['info'] = [];
            return json($this->Res);
        }
    }

    //需求单确认
    public function order_done(){
        $params = $this->request->param();
        $oid = $params['oid'];
        $uid = $params['uid'];

        //由待确认变成已确认
        $re = db('order')->where(['id'=>$oid])->update(['status'=>2,'done_id'=>$uid]);
        if($re){
            $this->Res['code'] = 1;
            $this->Res['info'] = [];
            return json($this->Res);
        }else{
            $this->Res['msg'] = '确认失败';
            return json($this->Res);
        }
    }

    //首页待确认列表
    public function ready_list(){
        $params = $this->request->param();
        $pid = $params['pid'];

        $data = db('qian')
        ->alias('q')
        // ->join('order o','o.id=q.oid')
        ->join('admin a','a.id=q.admin_id')
        ->where(['q.switch'=>1,'q.pid'=>$pid])
        ->field('q.*,a.nickname')
        ->limit(3)
        ->select();
        
        $this->Res['code'] = 1;
        $this->Res['info'] = $data;
        return json($this->Res);
    }

    public function base64_file_content($base64_file_content,$path,$name){
        
        $res = base64_decode($base64_file_content);
        
        // $re = file_put_contents('./test1.pdf',$res);

        $type = explode( '.',$name)[1];
        
        $new_file = $path."/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.time().".{$type}";
        
        if(file_put_contents($new_file,$res)){

            return  '/'.$new_file;
        }else{
            return false;
        }
    }

    public function del_order(){
        $params = $this->request->param();
        $id = $params['id'];

        $re = db('order')->where(['id'=>$id])->delete();
        if($re){
            $this->Res['code'] = 1;
            $this->Res['info'] = [];
            return json($this->Res);
        }else{
            $this->Res['msg'] = '确认失败';
            return json($this->Res);
        }
    }

    public function del_qian(){
        $params = $this->request->param();
        $id = $params['id'];

        $re = db('qian')->where(['id'=>$id])->delete();
        if($re){
            $this->Res['code'] = 1;
            $this->Res['info'] = [];
            return json($this->Res);
        }else{
            $this->Res['msg'] = '确认失败';
            return json($this->Res);
        }
    }

}